<template>
  <el-button type="text" @click="onSubmit" :disabled="isCountingDown">
    <span>获取验证码</span>
    <span v-show="isCountingDown">{{ countdown }}</span>
  </el-button>
</template>

<script>
export default {
  name: 'SendCodeBtn',
  props: {
    phone: {
      // type: Number, // 因为最开始的时候是空字符串，所以不加验证
      required: true,
    },
  },
  data() {
    return {
      timeCount: 60, // 倒计时时间
      countdown: 0, // 当前倒计时
      timer: null, // 计时器
    };
  },
  computed: {
    // 是否正在倒计时
    isCountingDown() { return this.countdown !== 0; },
  },
  methods: {
    // 发送验证码
    onSubmit() {
      this.$emit('checkPhone'); // 让表单验证手机号是否正确
      if (!this.$va.testPhone(this.phone)) return; // 手机号验证失败时不发送
      this.goCountdown();
      this.$api.other.sendCode(this.phone)
        .then(() => this.$message.success('验证码发送成功'))
        .catch(() => this.endCountdown());
    },
    // 开始倒计时
    goCountdown() {
      if (!this.timer) {
        this.countdown = this.timeCount;
        this.timer = setInterval(() => {
          this.countdown -= 1;
          if (this.countdown === 0) {
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 验证码发送失败时提前结束倒计时
    endCountdown() { if (this.timer) this.countdown = 5; },
  },
};
</script>

<style></style>
